<template>
	<view class="container">
		<custom-status-bar></custom-status-bar>
		<!-- 顶部导航 -->
		<view class="header">
			<view class="header-content">
				<view class="back-icon" @click="goBack">
					<uni-icons type="left" size="20" color="#1890ff"></uni-icons>
					<text>返回</text>
				</view>
				<text class="title">购物袋</text>
				<text class="edit-btn" @click="toggleEdit" v-if="isLoggedIn  && cartItems.length > 0">{{ editMode ? '完成' : '编辑'
				}}</text>
			</view>
		</view>

		<template v-if="isLoggedIn && cartItems.length > 0">
			<!-- 广告横幅 -->
			<image src="/static/bg.png" class="banner-image" />
			<!-- 购物袋列表 -->
			<view class="cart-list">
				<uv-checkbox-group class="checkbox-container" shape="circle" v-model="selectedIndex" >
					<uv-swipe-action>
						<uv-swipe-action-item v-for="(item, index) in cartItems" :key="index" :options="options"
							@click="deleteProduct(index)" :show="showDelete">
							<view class="cart-item" :id="index">
								<uv-checkbox :name="index"  :checked="isChecked"
									:id="index"></uv-checkbox>
								<image :src="image(item)" class="product-image" />
								<view class="product-info">
									<view class="name-spec">
										<text class="product-name">{{ item.name }}</text>
										<text class="product-spec">{{ item.rule }} </text>
									</view>
									<view class="product-spec"> {{ item.enname }}</view>
									<view class="price-count">
										<view class="product-price">¥{{ item.price }}</view>
										<view class="quantity-control">
											<uv-number-box v-model="item.count" @change="changeCount" :name="index" :min="0"
												:disableMinus="item.count <= 0" :showPlus="true">
												<template #minus>
													<view class="minus" :class="{ 'disabled': item.count <= 0 }">
														<uv-icon name="minus" size="12" :color="item.count <= 0 ? '#ccc' : '#000'">
														</uv-icon>
													</view>
												</template>
												<template #input>
													<text style="width: 50px;text-align: center;" class="input">
														{{ item.count }}
													</text>
												</template>
												<template #plus>
													<view class="plus">
														<uv-icon name="plus" color="#FFFFFF" size="12">
														</uv-icon>
													</view>
												</template>
											</uv-number-box>
										</view>
									</view>
								</view>
							</view>
						</uv-swipe-action-item>
					</uv-swipe-action>
				</uv-checkbox-group>
			</view>

		</template>

		<template v-else-if="isLoggedIn && cartItems.length === 0">
			<uv-empty mode="car" class="center"></uv-empty>
		</template>
		 <!-- 非登录状态 -->
		<template v-else-if="!isLoggedIn">
			<uv-empty mode="list" class="center">
				<view class="login-btn" @click="handleLogin">
					<text>登录</text>
				</view>
			</uv-empty>
		</template>
		<!-- 底部操作栏 -->
		<view class="action-bar" v-if="isLoggedIn  && cartItems.length > 0">
			<uv-checkbox-group class="checkboxContainer" shape="circle" v-model="isAll">
				<uv-checkbox label="全选" name="全选" @change="toggleAllSelection"></uv-checkbox>
			</uv-checkbox-group>
			<view class="right-section">
				<text class="total-price">合计: ¥{{ totalPrice }}</text>
				<uv-button type="default" size="small" class="submit-btn" :class="{ 'disabled': !selectedItems.length }"
					@click="handleSubmit">
					{{ submitText }}
				</uv-button>
			</view>
		</view>
	</view>
</template>
<script setup>
import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
import {
	ref,
	computed,
	reactive,
	watch,
	onMounted,
	onUnmounted
} from 'vue';
import {
	onShow
} from '@dcloudio/uni-app'
import {
	findAllShopcart,
	deleteShopcart,
	removeShopcart,
	commitShopcart
} from "@/api/index.js"



const isLoggedIn = ref(false)

const token = ref(uni.getStorageSync('coffee_token'))






// 编辑模式状态
const editMode = ref(false);
const isChecked = ref(false)
// 全选状态
const allSelected = ref(false);
const isAll = ref([])
const selectedIndex = ref([])
const showDelete = ref(true)
const cartItems = ref([]) // 购物车商品
const sids = ref([]) //选中的商品sid

 // const products = ref(uni.getStorageSync('product')||[]) //提交的商品



// onMounted(() => {
	
	
	
//  if(token.value){
// 	 isLoggedIn.value = true
//      getCurrentCart()
//      }else{
// 		 isLoggedIn.value = false 
// 	 }
// })




// 加载当前购车产品数据
onShow(() => {
 if(token.value){
	 isLoggedIn.value = true
     getCurrentCart()
     }else{
		 isLoggedIn.value = false 
	 }
})
// 产品图片
const image = (item) => {
	return 'https://placehold.co/300' || item.small_img;
}
const options = ref([{
	text: '删除',
	style: {
		backgroundColor: '#f56c6c'
	}
}])
// 选中的产品
const selectedItems = computed(() => {
	const result = cartItems.value.filter((item, index) => {
		return selectedIndex.value.includes(index);
	});
	//	console.log('选中的产品:', result); // 输出结果
	return result;
});

// 监听选中项变化，更新全选状态
watch(selectedIndex, (newVal) => {
	// 当选中项数量等于购物车商品总数时，表示全选
	if (newVal.length === cartItems.value.length && cartItems.value.length > 0) {
		isAll.value = ['全选'];
	} else {
		// 否则取消全选
		isAll.value = [];
	}
});




// 价格合计
const totalPrice = computed(() => {
	const total = selectedItems.value.reduce((sum, current) => {
		return sum + current.price * current.count;
	}, 0);
	//	console.log("totalPrice:", total.toFixed(2))
	return total.toFixed(2);
});
const submitText = computed(() => editMode.value ? '删除选择' : (selectedItems.value.length ? '提交订单' : '提交订单'));
// 编辑与完成
const toggleEdit = () => {
	editMode.value = !editMode.value;
	if (editMode.value) {
		// 进入编辑模式时取消全选
		allSelected.value = false;
		cartItems.value.forEach(item => item.selected = false);
	}
};
// 查询当前商品 
const getCurrentCart = async () => {
	const currentToken = uni.getStorageSync('coffee_token')
	if (currentToken) {
		uni.showLoading({
			title: '正在加载',
			icon: 'success'
		})
		const res = await findAllShopcart(currentToken)
		if (res.code === 5000) {
			cartItems.value = res.result
		}
		
		if (cartItems.value.length>0) {
			console.log("当前购物车：", cartItems.value)
		} else {
			console.log("当前购物车为空",)
		}
	}
	uni.hideLoading()
}
// 删除产品
const deleteProduct = async (index) => {
	//	console.log('点击的按钮索引:', index)
	// 删除对应索引产品
	// cartItems.value.splice(index, 1)
	showDelete.value = false
	
	uni.showModal({
		title:'删除',
		content:'要删除这个商品吗？',
		success:async(response)=>{
			if(response.confirm){
				const res = await removeShopcart(uni.getStorageSync('coffee_token'), JSON.stringify([cartItems.value[index].sid]))
				 console.log("删除的产品：", res)
				 cartItems.value.splice(index, 1)	
			}
			
		},
		
	})
	console.log("当前购物车剩余:", cartItems.value)
}



const toggleAllSelection = (name) => {
	//  console.log('toggleAllSelection:', name)
	if (name === true || (Array.isArray(name) && name.includes('全选'))) {
		//全选
		isChecked.value = true
		selectedIndex.value = generateIndexArray(cartItems.value.length)
	} else {
		// 取消全选
		isChecked.value = false
		selectedIndex.value = []
	}
};
// 计数器
const changeCount = ({
	value,
	name
}) => {
	console.log("changeCount value:", value) //当前计数器值
	console.log("changeCount name:", name) //当前产品索引值
	// 根据name 值判断是哪个产品的数量有更新
	cartItems.value[name].count = value
	
	console.log("当前购物车：",cartItems)
	
}
// 提交或者删除
const handleSubmit = async () => {
	if (editMode.value) {
		// 删除商品
		editMode.value = false;
		console.log("selectedIndex.value:", selectedIndex.value)
		sids.value = []
		selectedIndex.value.forEach((item) => {
			sids.value.push(cartItems.value[item].sid)
		})
		console.log("删除的sid：", sids.value)
		uni.showLoading({
			title: '正在删除',
			icon: 'success'
		})
		const res = await removeShopcart(uni.getStorageSync('coffee_token'), JSON.stringify(sids.value))
		if (res.code === 7000) {
			uni.showToast({
				title: res.msg,
				icon: 'success'
			})
		}

		// 删除选中的商品索引值
		safeRemoveIndexes(cartItems.value, selectedIndex.value)
		uni.hideLoading()
		console.log("cartItems:", cartItems.value)
	} else if (!editMode.value&&selectedItems.value.length) {
		
		// 提交
		sids.value = []
		selectedIndex.value.forEach((item) => {
			sids.value.push(cartItems.value[item].sid)
		})
		 //console.log("sids",sids.value)
		
		const res =await commitShopcart(uni.getStorageSync('coffee_token'),JSON.stringify(sids.value))
		
		console.log("commitShopcart",res)
		if(res.code===50000){
		  
		  // products.value=res.result	
		    
		    uni.setStorageSync('product',JSON.stringify(res.result))
		   
		}
		uni.showToast({
			title: '订单提交成功',
			icon: 'success',
			complete:()=>{
				uni.navigateTo({
					url:'/pages/orders/settlement'   // 订单结算
				})
			}
		});
		
	}
};
// 根据产品数量生成索引值数组
const generateIndexArray = (num) => {
	if (num === 0) return [];
	const n = Math.floor(Math.abs(num));
	return [...Array(n).keys()];
};
// 根据多个指定数组索引值删除数组arr元素
const safeRemoveIndexes = (arr, indexes) => {
	const uniqueSortedIndexes = [...new Set(indexes)].filter(i => i >= 0 && i < arr.length).sort((a, b) => b - a);
	uniqueSortedIndexes.forEach(i => arr.splice(i, 1));
}
const handleLogin = () => {
	uni.navigateTo({
		url: '/pages/protal/protal'
	})
};


const goBack = () => {
	const pages = getCurrentPages();
	if (pages.length > 1) uni.navigateBack();
		else  uni.switchTab({ url: '/pages/index/index' });
};
</script>
<style scoped>
.container {
	padding: 0 0 150rpx 0;
	background-color: #efefef;
	min-height: 100vh;
}

.header {
	position: relative;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100rpx;
	border-bottom: 1rpx solid #eee;
	background-color: #fff;
	padding: 0 20rpx;
}

.header-content {
	position: relative;
	width: 100%;
	height: 100%;
}

.back-icon {
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
	font-size: 28rpx;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}

.edit-btn {
	position: absolute;
	right: 0;
	top: 50%;
	transform: translateY(-50%);
	color: #1890ff;
	display: flex;
	align-items: center;
	font-size: 28rpx;
}

.banner-image {
	width: 100%;
	height: 150rpx;
	/* margin-top: 20rpx; */
}

.cart-list {
	padding: 20rpx 20rpx 0rpx 20rpx;
}

.uv-swipe-action {
	width: 100%;
}

.uv-swipe-action-item {
	margin-bottom: 20rpx;
	border-radius: 20rpx;
}

.cart-item {
	display: flex;
	flex-direction: row;
	justify-content: flex-start;
	align-items: center;
	padding: 20rpx;
	background: white;
	border-radius: 12rpx;
	/* margin-bottom: 20rpx; */
	position: relative;
}

.checkbox-container {
	/* width: 60rpx; */
	display: flex;
	align-items: center;
	justify-content: center;
}

.uv-checkbox-group {
	flex: 0;
	/* margin-right: 20rpx; */
}

.product-image {
	width: 180rpx;
	height: 180rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
	height: 180rpx;
	display: flex;
	flex-direction: column;
	flex-wrap: nowrap;
	justify-content: space-between;
}

.product-name {
	font-size: 28rpx;
	margin-right: 10rpx;
}

.product-spec {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 10rpx;
}

.price-count {
	color: red;
	font-weight: bold;
	font-size: 28rpx;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: flex-end;
}

.quantity-control {
	/* 	padding: 20rpx; */
	display: flex;
	flex-wrap: nowrap;
	justify-content: space-between;
}

.minus {
	width: 22px;
	height: 22px;
	border-width: 1px;
	border-color: #E6E6E6;
	border-style: solid;
	border-top-left-radius: 100px;
	border-top-right-radius: 100px;
	border-bottom-left-radius: 100px;
	border-bottom-right-radius: 100px;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	justify-content: center;
	align-items: center;
}

.minus.disabled {
	opacity: 0.5;
}

.input {
	padding: 0 10rpx;
	text-align: center;
}

.plus {
	width: 22px;
	height: 22px;
	background-color: #FF0000;
	border-radius: 50%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.qty-btn {
	width: 40rpx;
	height: 40rpx;
	background: #f5f5f5;
	border-radius: 8rpx;
	font-size: 28rpx;
}

.qty-text {
	width: 40rpx;
	text-align: center;
	margin: 0 10rpx;
}

.delete-btn {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	background: #ff4949;
	color: white;
	padding: 10rpx 20rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.action-bar {
	position: fixed;
	bottom: 100rpx;
	left: 0;
	right: 0;
	/* width: inherit; */
	z-index: 998;
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: white;
	padding: 10rpx 40rpx;
}

.right-section {
	display: flex;
	align-items: center;
	gap: 5rpx;
	/* 减小间距 */
	white-space: nowrap;
	flex-shrink: 0;
}

.total-price {
	font-size: 28rpx;
	white-space: nowrap;
	flex-grow: 1;
	/* 允许总价文本扩展 */
	flex-shrink: 1;
	/* 允许总价文本收缩 */
	text-align: right;
	/* 右对齐 */
	margin-right: 50rpx;
}

.submit-btn {
	background: #ff4949;
	color: white;
	border-radius: 40rpx;
	padding: 8rpx 30rpx;
	/* 减小 padding */
	font-size: 24rpx;
	/* 减小字体大小 */
	max-width: 200rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	flex-shrink: 0;
	/* 防止按钮被压缩 */
}

.submit-btn.disabled {
	opacity: 0.5;
	pointer-events: none;
}

.center {
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	width: 160px;
	height: 160px;

}



.login-btn {
	display: block;
	text-align: center;
	background-color: #232773;
	border: 1rpx solid #232773;
	color: white;
	border-radius: 40rpx;
	padding: 20rpx 0;
	font-size: 32rpx;
	margin-top: 40rpx;
	width: 200rpx;
}
</style>